const express = require('express')
const cors = require('cors')
const morgan = require('morgan')
const mongoose = require('mongoose')
const path = require('path')
require('dotenv').config()

// 导入路由
const authRoutes = require('./routes/auth.routes')
const userRoutes = require('./routes/user.routes')
const videoRoutes = require('./routes/video.routes')
const commentRoutes = require('./routes/comment.routes')
const settingsRoutes = require('./routes/setting.routes') 
const postRoutes = require('./routes/post.routes') 



// 导入中间件
const errorHandler = require('./middlewares/error.middleware')
const { authMiddleware } = require('./middlewares/auth.middleware')

// 创建Express应用
const app = express()

// 配置中间件
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(morgan('dev'))

// 配置静态文件服务
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));

// API 路由
app.use('/api/auth', authRoutes)
app.use('/api/user', authMiddleware, userRoutes)
app.use('/api/videos', videoRoutes)
app.use('/api/posts', postRoutes) 
app.use('/api/comments', commentRoutes)

// 导入管理员路由
const adminRoutes = require('./routes/admin.routes')
// 挂载管理员路由
app.use('/api/admin', adminRoutes)

// 将设置路由移到这里，避免与管理员路由冲突
app.use('/api/settings', settingsRoutes)

// 错误处理中间件
app.use(errorHandler)

// 连接MongoDB数据库
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/video_platform', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => {
  console.log('MongoDB数据库连接成功')
})
.catch((error) => {
  console.error('MongoDB数据库连接失败:', error)
  process.exit(1)
})

// 启动服务器
const PORT = process.env.PORT || 3000; // 根据 .env 文件或默认为 3000
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});